<template>
	<view class="count u-p-50">
		<u-form :model="form" ref="uForm" label-position="top">
			<u-form-item label="手机号" prop="phone" required>
				<u-input :maxlength="11" v-model="form.phone" type="number" />
			</u-form-item>
			<u-form-item label="验证码" prop="code" required>
				<u-input :maxlength="6" v-model="form.code" type="number" />
				<view slot="right">
					<u-toast ref="uToast"></u-toast>
					<u-verification-code :seconds="seconds" ref="uCode" @change="codeChange"></u-verification-code>
					<u-button ripple size="mini" style="background-color: rgb(42,90,164);color: #fff;" @tap="getCode">{{tips}}</u-button>
				</view>
			</u-form-item>
		</u-form>
		<u-button ripple shape="circle" class="u-m-t-30" style="background-color: rgb(42,90,164);color: #fff;" @click="submit">提交</u-button>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				tips: '',
				// refCode: null,
				seconds: 10,
				form: {
					phone: '',
					code: '',
				},
				rules: {
					phone: [{
						required: true,
						message: '请输入姓名',
						trigger: ['change', 'blur'],
					}, {
						validator: (rule, value, callback) => {
							return this.$u.test.mobile(value);
						},
						message: '手机号码不正确',
						trigger: ['change', 'blur'],
					}],
					code: [{
						required: true,
						message: '请输入验证码',
						trigger: ['change', 'blur']
					}]
				}
			};
		},
		methods: {
			codeChange(text) {
				this.tips = text;
			},
			getCode() {
				if(this.$u.test.mobile(this.form.phone)){
					if (this.$refs.uCode.canGetCode) {
						// 模拟向后端请求验证码
						uni.showLoading({
							title: '正在获取验证码'
						})
						setTimeout(() => {
							uni.hideLoading();
							// 这里此提示会被this.start()方法中的提示覆盖
							this.$u.toast('验证码已发送');
							// 通知验证码组件内部开始倒计时
							this.$refs.uCode.start();
						}, 2000);
					} else {
						this.$u.toast('倒计时结束后再发送');
					}
				}else{
					this.$u.toast('手机号输入错误');
				}
				
			},
			submit() {
				this.$refs.uForm.validate(valid => {
					if (valid) {
						console.log('验证通过');
					} else {
						console.log('验证失败');
					}
				});
			}
		},
		onReady() {
			this.$refs.uForm.setRules(this.rules);
		}
	}
</script>

<style lang="scss" scoped>

</style>
